<template>
	<view>
		<view>
			<uni-popup ref="popup" type="center" border-radius="10px 10px 0 0">
				<view class="option_main"
					style="background-color: #fff;display: flex;flex-direction: column;justify-content: space-around;padding: 25px;border-radius: 20px;">

					<view class="option_list">
						<view class="optin_items">
							<view class="optin_item">
								<uni-table>
									<uni-tr>
										<uni-th align="center">选项标签</uni-th>
										<uni-th align="center">选项内容</uni-th>
										<uni-th align="center">操作</uni-th>
									</uni-tr>
									<uni-tr v-for="(item,index) in current_pop_content.list">
										<uni-th align="center">{{item.value}}</uni-th>
										<uni-th align="center">{{item.label}}</uni-th>
										<uni-th align="center">
											<button @click="remove_option_item(item)" class="uni-button" size="mini"
												type="warn">删除</button>
										</uni-th>
									</uni-tr>
								</uni-table>
							</view>
						</view>
					</view>
					<view class=" option_nav"
						style="display: flex;flex-direction: column;justify-content: space-around;">
						<view class="form">
							<uni-section title="添加选项" type="line" padding>
								<view style="display: flex;flex-direction: row;align-items: center;padding: 10px;">
									选项标签:
									<uni-easyinput v-model="add_option_item.value"
										placeholder="请输入选项内容"></uni-easyinput>
								</view>
								<view style="display: flex;flex-direction: row;align-items: center;padding: 10px;">
									选项内容:
									<uni-easyinput v-model="add_option_item.label"
										placeholder="请输入选项标签"></uni-easyinput>
								</view>
							</uni-section>
						</view>
						<button @click="add_option_item_function">新增</button>
					</view>
				</view>
			</uni-popup>
		</view>
		<view class="uni-header">
			<view class="uni-group">
				<view class="uni-title"></view>
				<view class="uni-sub-title"></view>
			</view>
			<view class="uni-group">
				<!-- <input class="uni-search" type="text" v-model="query" @confirm="search" placeholder="请输入搜索内容" /> -->
				<!-- <button class="uni-button" type="default" size="mini" @click="search">搜索</button> -->
				<button class="uni-button" type="default" size="mini" @click="navigateTo('./add')">新增</button>
				<button class="uni-button" type="default" size="mini" :disabled="!selectedIndexs.length"
					@click="delTable">批量删除</button>
				<!--        <download-excel class="hide-on-phone" :fields="exportExcel.fields" :data="exportExcelData" :type="exportExcel.type" :name="exportExcel.filename">
          <button class="uni-button" type="primary" size="mini">导出 Excel</button>
        </download-excel> -->
			</view>
		</view>
		<view class="uni-container">
			<unicloud-db ref="udb" :collection="collectionList" :where="where" page-data="replace" :orderby="orderby"
				:getcount="true" :page-size="options.pageSize" :page-current="options.pageCurrent"
				v-slot:default="{data,pagination,loading,error,options}" :options="options" loadtime="manual"
				@load="onqueryload">
				<uni-table ref="table" :loading="loading" :emptyText="error.message || '没有更多数据'" border stripe
					type="selection" @selection-change="selectionChange">
					<uni-tr>
						<uni-th align="center" filter-type="range" @filter-change="filterChange($event, 'index')"
							sortable @sort-change="sortChange($event, 'index')">题目序号</uni-th>
						<uni-th align="center">活动名称</uni-th>
						<uni-th align="center" filter-type="search" @filter-change="filterChange($event, 'topic')"
							sortable @sort-change="sortChange($event, 'topic')">题干</uni-th>
						<uni-th align="center" filter-type="search" @filter-change="filterChange($event, 'score')"
							sortable @sort-change="sortChange($event, 'score')">分数</uni-th>
						<uni-th align="center" filter-type="search" @filter-change="filterChange($event, 'correct')"
							sortable @sort-change="sortChange($event, 'correct')">正确答案</uni-th>
						<!-- 						<uni-th align="center" filter-type="search" @filter-change="filterChange($event, 'errorRes')"
							sortable @sort-change="sortChange($event, 'errorRes')">错误反馈</uni-th> -->
						<uni-th align="center">操作</uni-th>
					</uni-tr>
					<uni-tr v-for="(item,index) in data" :key="index">
						<uni-td align="center">{{item.index}}</uni-td>
						<uni-td
							align="center">{{item.belong_hd && item.belong_hd[0] && item.belong_hd[0].text}}</uni-td>
						<uni-td align="center">{{item.topic}}</uni-td>
						<uni-td align="center">{{item.score}}</uni-td>
						<uni-td align="center">{{item.correct}}</uni-td>
						<!-- <uni-td align="center">{{item.errorRes}}</uni-td> -->
						<uni-td align="center">
							<view class="uni-group">
								<button @click="navigateTo('./edit?id='+item._id, false)" class="uni-button" size="mini"
									type="primary">修改</button>
								<button @click="edit_options(item)" class="uni-button" size="mini"
									type="default">编辑选项</button>
								<button @click="confirmDelete(item._id)" class="uni-button" size="mini"
									type="warn">删除</button>
							</view>
						</uni-td>
					</uni-tr>
				</uni-table>
				<view class="uni-pagination-box">
					<uni-pagination show-icon :page-size="pagination.size" v-model="pagination.current"
						:total="pagination.count" @change="onPageChanged" />
				</view>
			</unicloud-db>
		</view>
	</view>
</template>

<script>
	import {
		enumConverter,
		filterToWhere
	} from '../../js_sdk/validator/abu-question-info.js';

	const db = uniCloud.database()

	const options_item = db.collection("abu-question-option")


	// 表查询配置
	const dbOrderBy = '' // 排序字段
	const dbSearchFields = [] // 模糊搜索字段，支持模糊搜索的字段列表。联表查询格式: 主表字段名.副表字段名，例如用户表关联角色表 role.role_name
	// 分页配置
	const pageSize = 20
	const pageCurrent = 1

	const orderByMapping = {
		"ascending": "asc",
		"descending": "desc"
	}

	export default {
		data() {
			return {
				add_option_item: {
					label: '',
					value: ''
				},
				current_pop_content: {
					list: [],
					tigan: {}
				},
				collectionList: [db.collection('abu-question-info').field('index,belong_hd,topic,score,correct,errorRes')
					.getTemp(), db.collection('abu-answering-activity').field('title as text, _id').getTemp()
				],
				query: '',
				where: '',
				orderby: dbOrderBy,
				orderByFieldName: "",
				selectedIndexs: [],
				options: {
					pageSize,
					pageCurrent,
					filterData: {},
					...enumConverter
				},
				imageStyles: {
					width: 64,
					height: 64
				},
				exportExcel: {
					"filename": "abu-question-info.xls",
					"type": "xls",
					"fields": {
						"题目序号": "index",
						"活动名称": "belong_hd",
						"题干": "topic",
						"分数": "score",
						"正确答案": "correct",
						"错误反馈": "errorRes"
					}
				},
				exportExcelData: []
			}
		},
		onLoad() {
			this._filter = {}
		},
		onReady() {
			this.$refs.udb.loadData()
		},
		methods: {
			add_option_item_function() {
				const current_tigan = this.current_pop_content.tigan;
				if (this.add_option_item.label && this.add_option_item.value) {
					this.current_pop_content.list.push({
						value: this.add_option_item.value,
						label: this.add_option_item.label
					})
					options_item.add({
						belong_qs: current_tigan._id,
						value: this.add_option_item.value,
						label: this.add_option_item.label
					}).then(res => {
						uni.showToast({
							title: '操作成功'
						});
					}).catch(e => {
						uni.showToast({
							title: '操作失败'
						});
					})
				} else {
					uni.showToast({
						title: '请输入完整信息'
					});
				}

			},
			// 删除某一个题目的一个选项
			remove_option_item(item) {
				uni.showModal({
					title: '提示',
					content: '确定要删除吗',
					showCancel: true,
					cancelText: '取消',
					confirmText: '删除',
					success: res => {
						if (res.confirm) {
							this.current_pop_content.list = this.current_pop_content.list.filter(item1 => item1
								._id != item._id);
							options_item.where(`_id=="${item._id}"`).remove().then(res => {
								uni.showToast({
									title: '操作成功'
								});
							}).catch(e => {
								console.log(e);
								uni.showToast({
									title: '操作失败'
								});
							})
						}

						if (res.cancel) {
							return
						}
					},
					fail: () => {},
					complete: () => {}
				});
			},
			// 打开选项编辑框
			edit_options(item) {
				options_item.where({
					belong_qs: item._id
				}).get().then(res => {
					const res_data = res.result.data;
					console.log(res_data);
					this.current_pop_content.list = res_data
					this.current_pop_content.tigan = item
				}).finally(res => {
					this.$refs.popup.open('center')
				})

			},
			onqueryload(data) {
				this.exportExcelData = data
			},
			getWhere() {
				const query = this.query.trim()
				if (!query) {
					return ''
				}
				const queryRe = new RegExp(query, 'i')
				return dbSearchFields.map(name => queryRe + '.test(' + name + ')').join(' || ')
			},
			search() {
				const newWhere = this.getWhere()
				this.where = newWhere
				this.$nextTick(() => {
					this.loadData()
				})
			},
			loadData(clear = true) {
				this.$refs.udb.loadData({
					clear
				})
			},
			onPageChanged(e) {
				this.selectedIndexs.length = 0
				this.$refs.table.clearSelection()
				this.$refs.udb.loadData({
					current: e.current
				})
			},
			navigateTo(url, clear) {
				// clear 表示刷新列表时是否清除页码，true 表示刷新并回到列表第 1 页，默认为 true
				uni.navigateTo({
					url,
					events: {
						refreshData: () => {
							this.loadData(clear)
						}
					}
				})
			},
			// 多选处理
			selectedItems() {
				var dataList = this.$refs.udb.dataList
				return this.selectedIndexs.map(i => dataList[i]._id)
			},
			// 批量删除
			delTable() {
				this.$refs.udb.remove(this.selectedItems(), {
					success: (res) => {
						this.$refs.table.clearSelection()
					}
				})
			},
			// 多选
			selectionChange(e) {
				this.selectedIndexs = e.detail.index
			},
			confirmDelete(id) {
				this.$refs.udb.remove(id, {
					success: (res) => {
						this.$refs.table.clearSelection()
					}
				})
			},
			sortChange(e, name) {
				this.orderByFieldName = name;
				if (e.order) {
					this.orderby = name + ' ' + orderByMapping[e.order]
				} else {
					this.orderby = ''
				}
				this.$refs.table.clearSelection()
				this.$nextTick(() => {
					this.$refs.udb.loadData()
				})
			},
			filterChange(e, name) {
				this._filter[name] = {
					type: e.filterType,
					value: e.filter
				}
				let newWhere = filterToWhere(this._filter, db.command)
				if (Object.keys(newWhere).length) {
					this.where = newWhere
				} else {
					this.where = ''
				}
				this.$nextTick(() => {
					this.$refs.udb.loadData()
				})
			}
		}
	}
</script>

<style>
</style>